CREATE PROCEDURE CalculateWinningResultsForCustomers
	@ParamMatchScheduleId int,
	@ParamBettingId int,
	@ParamMatchType int
AS
BEGIN


DECLARE @BettingId int
DECLARE @CustomerBettingId int
DECLARE @BetFor char(1)
DECLARE @CBRate varchar(50)
DECLARE @LagadiRate varchar(50)
DECLARE @KhadhiRate varchar(50)
DECLARE @Over varchar(50)
DECLARE @Runs varchar(50)
DECLARE @BettingType varchar(50)

DECLARE update_cursor CURSOR
	FOR 
		SELECT DISTINCT 
		B.Id AS BettingId,
		CB.Id AS CustomerBettingId,
		CB.BetFor,
		CB.Rate,
		B.LagadiRate,
		B.KhadhiRate,
		MSR.[Over],
		MSR.Runs,
		BT.[Type] AS BettingType
		from MatchSchedule MS
		INNER JOIN CustomerBetting CB ON MS.Id = CB.MatchSchduleId
		INNER JOIN Betting B ON CB.BettingId = B.Id
		INNER JOIN BettingType BT ON B.BettingTypeId = BT.Id
		INNER JOIN MatchSessionResult MSR ON B.[Over] = MSR.[Over]
		WHERE MS.IsResultDeclared = 0 AND -- whos result is not yet decelared
		MS.Id = @ParamMatchScheduleId AND -- as a parameter of Match Schedule 
		BT.Id = @ParamBettingId AND -- as a parameter of Betting Type
		MS.MatchType = @ParamMatchType -- as a parameter of Match Type
		ORDER BY B.Id
OPEN update_cursor
FETCH NEXT FROM update_cursor 
INTO @BettingId, @CustomerBettingId, @BetFor, @CBRate, @LagadiRate, @KhadhiRate, @Over, @Runs, @BettingType

WHILE @@FETCH_STATUS = 0
    BEGIN
		
		IF @BettingType = 'Session'
			BEGIN
				IF @BetFor = 'L'
					BEGIN
						IF @LagadiRate >= @Runs
							BEGIN
								UPDATE CustomerBetting
								SET BettingAmount = @CBRate,
								BettingGain = '+'
								WHERE Id = @CustomerBettingId
							END
						ELSE
							BEGIN
								UPDATE CustomerBetting
								SET BettingAmount = @CBRate,
								BettingGain = '-'
								WHERE Id = @CustomerBettingId
							END
					END
				ELSE
					BEGIN
						IF @KhadhiRate <= @Runs
							BEGIN
								UPDATE CustomerBetting
								SET BettingAmount = @CBRate,
								BettingGain = '+'
								WHERE Id = @CustomerBettingId
							END
						ELSE
							BEGIN
								UPDATE CustomerBetting
								SET BettingAmount = @CBRate,
								BettingGain = '-'
								WHERE Id = @CustomerBettingId
							END
					END
			END
		ELSE
			BEGIN
				PRINT 'Match Calculations here.'
			END
	FETCH NEXT
    FROM update_cursor
	INTO @BettingId, @CustomerBettingId, @BetFor, @CBRate, @LagadiRate, @KhadhiRate, @Over, @Runs, @BettingType

	END
CLOSE update_cursor
DEALLOCATE update_cursor

END